    //
//  LoginVC_iPad.m
//  WRY
//
//  Created by zhong sckj on 10-10-12.
//  Copyright 2010 __MyCompanyName__. All rights reserved.
//

#import "LoginVC_iPad.h"
#import "AppDelegate_iPad.h"
#import "CommonJson.h"
#import "WebPath.h"
#import "UIDevice+IdentifierAddition.h"

@implementation LoginVC_iPad{
    UITapGestureRecognizer *tapReco;
}
#define LOGINVIEWX 322.0
@synthesize loginView,loginNameField,loginPwdField;

@synthesize popSettingPath,popController;

@synthesize loginUserName,loginUserPwd,deviceType,deviceCode;

- (void)viewDidLoad {
    [super viewDidLoad];
    self.deviceType=@"0102";
    
    self.deviceCode=[[UIDevice currentDevice]uniqueDeviceIdentifier];
    
    
    tapReco=[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapAction:)];
    tapReco.delegate=self;
    [self.view addGestureRecognizer:tapReco];
    
    
    [self initalLoginView];

	[self checkLoginInfo];
}
- (void)dealloc {
    [super dealloc];
	[popController release];
	[popSettingPath release];
	[loginView release];
	[loginNameField release];
	[loginPwdField release];
}
#pragma mark -
#pragma mark 设置webservice路径按钮
-(IBAction)settWetPathClick:(id)sender
{
	if (self.popSettingPath==nil) {
		SettingPathVC_iPad *setwebpath=[[SettingPathVC_iPad alloc]init];
		[setwebpath setContentSizeForViewInPopover:CGSizeMake(320,396)];
		setwebpath.loginVc=self;
        setwebpath.fromTag=100;
		self.popSettingPath=setwebpath;
		[setwebpath release];
	}
	UINavigationController *navi=[[UINavigationController alloc]
								  initWithRootViewController:self.popSettingPath];
	UIPopoverController *popVc=[[UIPopoverController alloc]initWithContentViewController:navi];
	[navi release];
	popVc.delegate=self;
	self.popController=popVc;
	[popVc release];
	UIButton *btn=(UIButton *)sender;
	[self.popController presentPopoverFromRect:btn.bounds inView:btn permittedArrowDirections:UIPopoverArrowDirectionUp animated:YES];	
	
}
#pragma mark UIPopoverControllerDelegate 
- (BOOL)popoverControllerShouldDismissPopover:(UIPopoverController *)popoverController {
	return YES;
}
- (void)popoverControllerDidDismissPopover:(UIPopoverController *)popoverController {
	[popoverController release];
}
- (void)showLoginFailed {
	UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"error" message:@"Login failed" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
	[alert show];
	[alert release];
}
-(void)showAlert:(NSString *)message
{
	UIAlertView *alert=[[UIAlertView alloc]initWithTitle:@"提示" message:message 
												delegate:self 
									   cancelButtonTitle:@"OK" 
									   otherButtonTitles:nil];
	[alert show];
	[alert release];
}
// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)loadView
{
	[super loadView];
	[self initalLoginView];
	//监听键盘的通知
	[[NSNotificationCenter defaultCenter] addObserver:self 
											 selector:@selector(eventForKeyShow:) 
												 name:@"UIKeyboardWillShowNotification" 
											   object:nil];
	
	[[NSNotificationCenter defaultCenter]addObserver:self 
											selector:@selector(eventForKeyHidden:) 
												name:@"UIKeyboardWillHideNotification" 
											  object:nil];
}

- (void)checkLoginInfo {
	[self showLoading:512.0 centerY:400.0];
	NSString *requestString = [NSString stringWithFormat:@"DeviceTypeID=%@&DeviceOnlyCode=%@",self.deviceType,self.deviceCode];
	[[CommonJson sharedInstance] requestToPath:[WebPath loginPath]
									methodName:@"GetUserLoginInfo"
									bodyString:requestString 
									 targetObj:self 
							  targetMethodName:@"eventForCheckLogin:"
									notifiName:@"CheckLoginInfo"];
	
}
- (void)eventForCheckLogin:(NSNotification *)notification {
	[[CommonJson sharedInstance] removeTarget:self notiName:[notification name]];
	[self hideLoading];
	NSObject *object = [notification object];
	if ([object isKindOfClass:[NSDictionary class]])
	{
		NSDictionary *dict = (NSDictionary *)object;
		if ([[dict objectForKey:@"Status"] intValue]==1)
		{
			NSDictionary *data = [dict objectForKey:@"Data"];
			[self loginFor:[data objectForKey:@"UserName"] password:[data objectForKey:@"Password"]];
            return;
        }
    }

    [self showLoginView];
	
}
- (void)loginFor:(NSString *)user password:(NSString *)pwd {
	
    [self showLoading:0 centerY:0];
    self.loginUserName=user;
    self.loginUserPwd=pwd;
	NSString *body = [NSString stringWithFormat:@"UserName=%@&Password=%@&DeviceTypeID=%@&DeviceOnlyCode=%@",user,pwd,self.deviceType,self.deviceCode];
	[[CommonJson sharedInstance] requestToPath:[WebPath loginPath]
									methodName:@"Login"
									bodyString:body 
									 targetObj:self 
							  targetMethodName:@"eventForLogin:" 
									notifiName:@"LoginAction"];
}
- (void)eventForLogin:(NSNotification *)notification {
	
	[[CommonJson sharedInstance] removeTarget:self notiName:[notification name]];
    [self hideLoading];
	NSObject *object = [notification object];
	if ([object isKindOfClass:[NSDictionary class]]) {
		NSDictionary *dict = (NSDictionary *)object;
        NSString *loginGuid=(NSString *)[dict objectForKey:@"Data"];
        
        if ([loginGuid length]>=36)
        {
            [loginNameField resignFirstResponder];
            [loginPwdField resignFirstResponder];
            
            [[AppDelegate_iPad currentDelegate] setGUID:[dict objectForKey:@"Data"]];
			[self setSystemSource];
            
            //保存用户名密码
            [[NSUserDefaults standardUserDefaults]setObject:self.loginUserName forKey:@"LoginName"];
            [[NSUserDefaults standardUserDefaults]setObject:self.loginUserPwd forKey:@"LoginPwd"];
            [[NSUserDefaults standardUserDefaults]setObject:self.deviceType forKey:@"DeviceType"];
            [[NSUserDefaults standardUserDefaults]setObject:self.deviceCode forKey:@"DeviceOnlyCode"];
            [[NSUserDefaults standardUserDefaults]setObject:@"10028" forKey:@"SystemID"];
            
            
            //设置用户行政区
            [[AppDelegate_iPad currentDelegate] setUserCantonCodes:@""];
            //设置显示的行政区名称
            [[AppDelegate_iPad currentDelegate] setShowCantonName:@"江苏省"];
            //设置用户权限 
            [[AppDelegate_iPad currentDelegate] setUserType:@"0"];
        }
        else 
        {
            NSString *stringMessage=@"";
            switch ([loginGuid intValue]) 
            {
                case 0:
                    stringMessage=@"登录失败！";
                    break;
                case 1:
                    stringMessage=@"该设备已被停用,\n请与管理员联系！";
                    break;
                case 2:
                    stringMessage=@"该账号已经与其它设备绑定,\n必须解绑才能重新登入！";
                    break;
                default:
                    break;
            }
            [self showAlertMessage:stringMessage];
            [self showLoginView];
        }
	}
}
- (void)setSystemSource {
    [self showLoading:0 centerY:0];
	NSString *body = [NSString stringWithFormat:@"LoginGuid=%@&SystemID=%@",[[AppDelegate_iPad currentDelegate] GUID],@"10028"];
	[[CommonJson sharedInstance] requestToPath:[WebPath loginPath]
									methodName:@"SetServiceSource"
									bodyString:body 
									 targetObj:self 
							  targetMethodName:@"eventForSetSource:" 
									notifiName:@"SetSystemSource"];
}
- (void)eventForSetSource:(NSNotification *)notification
{
    [self hideLoading];
    [[CommonJson sharedInstance] removeTarget:self notiName:[notification name]];
	NSObject *object = [notification object];
	if ([object isKindOfClass:[NSDictionary class]]) 
	{
		NSDictionary *dict = (NSDictionary *)object;
		if ([[dict objectForKey:@"Status"] intValue]==1)
		{
			//移除键盘通知
			[[NSNotificationCenter defaultCenter]removeObserver:self name:@"UIKeyboardWillShowNotification" object:nil];
			[[NSNotificationCenter defaultCenter]removeObserver:self name:@"UIKeyboardWillHideNotification" object:nil];
			//转到首页
			[[AppDelegate_iPad currentDelegate] addRootVc];
		}
	}
	
}
#pragma mark 窗体控制
-(void)initalLoginView
{
	[UIApplication sharedApplication].networkActivityIndicatorVisible=YES;
	[loginView setBackgroundColor:[UIColor clearColor]];
	[loginView setFrame:CGRectMake(LOGINVIEWX,SCREEN_HEIGHT, loginView.frame.size.width, loginView.frame.size.height)];
//    [loginView setHidden:YES];

}
-(void)showLoginView
{

	[UIApplication sharedApplication].networkActivityIndicatorVisible=NO;
//	[UIView beginAnimations:nil context:NULL];
//	[UIView setAnimationDelegate:self];
//	[UIView setAnimationCurve:UIViewAnimationCurveEaseInOut]; 
//	[UIView setAnimationDuration:1];
	[loginView setFrame:CGRectMake(LOGINVIEWX, 300, loginView.frame.size.width, loginView.frame.size.height)];
//	[UIView commitAnimations];

   
}
-(IBAction)loginSurebuttonClick:(id)sender
{
	
	[loginNameField resignFirstResponder];
	[loginPwdField resignFirstResponder];

	
	NSString *loginName=loginNameField.text;
	NSString *loginPwd=loginPwdField.text;
	if ([loginName isEqualToString:@""] || [loginPwd isEqualToString:@""])
	{
		[self showAlert:@"用户名和密码不能为空！"];
	}
	else
	{
		[self showLoading:512.0 centerY:400.0];
		[self loginFor:loginNameField.text password:loginPwdField.text];
	}
}
-(void)pushTopLoginWindow
{
	[UIView beginAnimations:nil context:NULL];
	[UIView setAnimationDelegate:self];
	[UIView setAnimationCurve:UIViewAnimationCurveEaseInOut]; 
	[UIView setAnimationDuration:0.3];
	[loginView setFrame:CGRectMake(LOGINVIEWX, 220, loginView.frame.size.width, loginView.frame.size.height)];
	[UIView commitAnimations];
}

#pragma mark 键盘事件
- (void)eventForKeyShow:(NSNotification *)notification
{
	[self pushTopLoginWindow];
	
}
- (BOOL)eventForKeyHidden:(NSNotification *)notification
{
	[loginNameField resignFirstResponder];
	[loginPwdField resignFirstResponder];
	[UIView beginAnimations:nil context:NULL];
	[UIView setAnimationDelegate:self];
	[UIView setAnimationCurve:UIViewAnimationCurveEaseInOut]; 
	[UIView setAnimationDuration:0.3];
	[loginView setFrame:CGRectMake(LOGINVIEWX, 300, loginView.frame.size.width, loginView.frame.size.height)];
	[UIView commitAnimations];
	return YES;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Overriden to allow any orientation.
    if (interfaceOrientation==UIInterfaceOrientationLandscapeLeft || interfaceOrientation==UIInterfaceOrientationLandscapeRight)
	{
		return YES;
	}
    else 
	{
		return NO;
	}
}


- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}


- (void)viewDidUnload {
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

#pragma mark - touch事件
-(void)tapAction:(UIGestureRecognizer *)recognizer{
    
}
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch{
    
    return YES;
}


@end
